// packageA/pages/reportSend/reportSend.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import * as echarts from '../../../ec-canvas/echarts';
const util = require('../../../utils/util');

//图表对象
let Chart1=null;
let Chart2=null;

//去掉尾部的0
const regexp=/(?:\.0*|(\.\d+?)0+)$/;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //图片前缀
    prefix:'http://bangnizu.oss-cn-hangzhou.aliyuncs.com/bangni/images/',
    //用户信息
    user:{},
    //权限
    authority:{},
    //图表
    ec1: {
      //延迟加载
      lazyLoad: true
    },
    ec2: {
      lazyLoad: true
    },
    //是否显示图表（避免遮挡）
    showChart1:true,
    showChart2:true,
    //无数据
    showNoData1:false,
    showNoData2:false,
    //图表配置
    chartSet1:{
      //图表类型
      type:'line',
      //颜色
      barColor:'#ccc',
      //y轴标题
      title:''
    },
    chartSet2:{
      //图表类型
      type:'bar',
      //颜色
      barColor:'#ccc',
      //y轴标题
      title:'（%）'
    },
    //项目id
    projectId:null,
    //项目名称
    projectName:'',
    //显示的当前月份
    currentMonth:util.timeFormatMonth(new Date()),
    //选择框的当前日期
    currentDate: new Date().getTime(),
    //选择框的最小月份
    minDate:util.beforeMonth(4).getTime(),
    //选择框的最大月份
    maxDate: new Date().getTime(),
    //简报看板数据
    boardData:{},
    all:0,
    todayNum:0,
    recent3:0,
    recent15:0,
    repairNum:0,
    battery:0,
    //是否显示效率排名
    showEfficiency:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let currentUser = app.globalData.userInfo;
    if(currentUser){
      //登录用户
      this.setData({
        user: currentUser,
        projectName: currentUser.departObj[0].name,
        authority:app.globalData.authority
      })

      //简报看板
      this.getDataCount();

      //每日工作量
      this.getCostData();

      //是否显示效率排名
      if(currentUser.departObj[0].hasReport==true){
        this.setData({
          showEfficiency: true
        })
      }
    }else{
      wx.redirectTo({
        url: "/pages/login/login?reportSend="+'1'
      })
    }
  },

  //数据面板数据
  getDataCount(){
    let param={
      minRange: 3,
      midRange: 7,
      maxRange: 15
    }

    CommonService.personCenterCounts(param).then(res=>{
      if(res.data.data){
        let result=res.data.data;
        console.log('简报看板');
        console.log(result);

        this.setData({
          boardData:result,
          all: result.all ? result.all.length : 0,
          todayNum: result.countToday ? result.countToday.length : 0,
          recent3: result.count3Day ? result.count3Day.length : 0,
          recent15: result.count15Day ? result.count15Day.length : 0,
          repairNum: result.countRepair ? result.countRepair.length : 0,
          battery: result.lowPower ? result.lowPower.length : 0
        })

        //设备出勤率
        this.getUseTimeData();
      }
    }).catch((error) => {
    })
  },

  //点击总设备
  goToEquipment(){
    wx.navigateTo({
      url: "/pages/equipmentList/equipmentList"
    })
  },

  //点击简报看板
  goToSomeEquipment(e){
    let key=e.currentTarget.dataset.key;
    let boardData=this.data.boardData;
    let arr=boardData[key];
    //跳转设备列表并传参imei
    if(arr && arr.length){
      wx.navigateTo({
        url: "/pages/equipmentList/equipmentList?imeiArr="+JSON.stringify(arr)
      })
    }
  },

  //获取每日工作量数据
  getCostData(){
    //图表组件
    this.echartsComponnet1 = this.selectComponent('#mychart1');

    let today=new Date();
    let todayStr=util.timeFormatDay(new Date());
    let day7=util.timeFormatDay(util.countPrevDay(today,6));

    let param={
      startTime: day7,
      endTime: todayStr
    }

    CommonService.findCostData(param).then(res=>{
      console.log(res);
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        this.setData({
          showNoData1:false,
          showChart1: true
        })

        let result=res.data.data.result;
        console.log('每日工作量');
        console.log(result);

        let isAll0=result.every(item=>{
          return item.staResult==0
        });

        if(isAll0){
          this.setData({
            showNoData1:true,
            showChart1: false
          })
        }else{
          //按日期分组
          let listArr = [];
          result.forEach(function (el, index) {
            for (let i = 0; i < listArr.length; i++) {
              if (listArr[i].staValue == el.staValue) {
                listArr[i].con.push(el);
                return;
              }
            }
            listArr.push({
              staValue: el.staValue,
              con: [el]
            });
          });

          //没有值的置为0
          listArr.forEach(item => {
            let con=item.con;
            if(con.length==1){
              if(con[0].workUnit=='㎡'){
                item.con.push({
                  id:0,
                  staResult: 0,
                  workUnit: "km",
                  staValue: con[0].staValue
                });
              }else if(con[0].workUnit=='km'){
                item.con.push({
                  id:0,
                  staResult: 0,
                  workUnit: "㎡",
                  staValue: con[0].staValue
                });
              }
            }
          });

          //图表数据
          let xData=[];
          let y1Data=[];
          let y2Data=[];
          let yDataArr=[];

          listArr.forEach(item => {
            if(item.staValue){
              xData.push(item.staValue.slice(5));
              let con=item.con;

              for(let i=0;i<con.length;i++){
                if(con[i].workUnit=='㎡'){
                  y1Data.push(parseInt(con[i].staResult));
                }
                if(con[i].workUnit=='km'){
                  y2Data.push(parseInt(con[i].staResult*1000));
                }
              }
            }
          });

          yDataArr.push({
            name: '总工作面积（㎡）',
            type: 'line',
            data: y1Data,
            color: '#dc5266'
          },{
            name: '总工作里程（m）',
            type: 'line',
            data: y2Data,
            color: '#264d71'
          });

          let chartData={
            xData:xData,
            yData:yDataArr
          }

          //判断图表是否第一次绘制
          this.isHaveChart(Chart1,this.echartsComponnet1,this.data.chartSet1,chartData);
        }

      }else{
        this.setData({
          showNoData1:true,
          showChart1: false
        })
      }
    }).catch((error) => {
    })
  },

  //获取设备出勤率数据
  getUseTimeData(){
    //图表组件
    this.echartsComponnet2 = this.selectComponent('#mychart2');

    let today=new Date();
    let todayStr=util.timeFormatDay(new Date());
    let day7=util.timeFormatDay(util.countPrevDay(today,6));

    let param={
      startTime: day7,
      endTime: todayStr
    }

    CommonService.findAttendanceRate(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        this.setData({
          showNoData2:false,
          showChart2: true
        })

        let result=res.data.data.result;
        console.log('出勤率');
        console.log(result);

        //图表数据
        let xData=[];
        let yData=[];
        for(let i=0;i<result.length;i++){
          xData.push(result[i]._id.slice(5));
          let len=result[i].results;
          let all=this.data.all;
          let rate=(len/all*100).toFixed(0).replace(regexp,'$1');
          yData.push(rate);
        }

        let chartData={
          xData:xData,
          yData:[{
              type: 'bar',
              data: yData,
              //color: '#1f4e79',
              barWidth : '15px',
              itemStyle: {
                normal: {
                  label: {
                    show: true,
                    position: 'top',
                    color:"#80242d"
                  },
                  color: new echarts.graphic.LinearGradient(
                    0, 0, 0, 1,
                    [{
                        offset: 0,
                        color: '#db0000'
                      },
                      {
                        offset: 1,
                        color: '#1f4e79'
                      }
                    ]
                  )
                }
              }
          }]
        }

        //判断图表是否第一次绘制
        this.isHaveChart(Chart2,this.echartsComponnet2,this.data.chartSet2,chartData);

      }else{
        this.setData({
          todayNum: 0,
          showNoData2:true,
          showChart2: false
        })
      }
    }).catch((error) => {
    })
  },

  //判断图表是否第一次绘制
  isHaveChart(chartObj,componnetObj,setObj,dataObj){
    if (!chartObj){
      //如果是第一次绘制，则初始化图表
      this.init_echarts(chartObj,componnetObj,setObj,dataObj);
    }else{
      //更新图表数据
      this.setOption(chartObj,setObj,dataObj);
    }
  },

  //初始化图表
  init_echarts: function (chartObj,componnetObj,setObj,dataObj) {
    componnetObj.init((canvas, width, height) => {
      chartObj = echarts.init(canvas, null, {
        width: width,
        height: height
      });

      this.setOption(chartObj,setObj,dataObj);

      return chartObj;
    });
  },

  //更新图表数据
  setOption: function (chartObj,setObj,dataObj) {
    //清除
    chartObj.clear();
    //设置新数据
    chartObj.setOption(this.getOption(chartObj,setObj,dataObj));
  },

  //指定图表的配置项和数据
  getOption: function (chartObj,setObj,dataObj) {
    //文字颜色
    let fontColor='#666';

    let option = {
      legend: {
        //icon: 'arrow',
        textStyle: {
          color: '#666',
          padding: [0, 30, 0, 0]
        },
        x: 'right',
        y: 'top'
      },
      grid: {
        left: '2%',
        right: '3%',
        top: '20%',
        bottom: '7%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        axisLabel: {
          //show: false,
          color: fontColor,
          fontSize : 14,
          interval:0,
          //rotate:10
        },
        axisLine: {
          lineStyle: {
            color: setObj.barColor
          }
        },
        data: dataObj.xData,
      },
      yAxis: {
        type: 'value',
        name: setObj.title,
        axisLabel: {
          //show: false,
          color: fontColor,
          fontSize : 13,
        },
        axisLine: {
          lineStyle: {
            color: setObj.barColor
          }
        },
        splitLine: {
          lineStyle: {
            color: '#eee'
          }
        }
      },
      series:dataObj.yData
    };

    return option;
  },

  //隐藏图表
  hideChart(){
    this.setData({
      showChart1:false,
      showChart2:false
		})
  },

  //显示图表
  showChart(){
    this.setData({
      showChart1:true,
      showChart2:true
		})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
